package com.hhly.rabbitmq.rpc;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import com.hhly.rabbitmq.RabbitMQUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class RPCClient {
	 static  Channel channel;
     public static void main(String[] args) throws Exception {
    	 channel = RabbitMQUtil.getChannel();
    	 for (int i = 2; i < 30; i++) {
			System.out.println(call(String.valueOf(i)));
		 }
    	 System.out.println("end");
    	 channel.close();
	 }
     
     public static String  call(String message) throws Exception{
    	 
    	 String replyQueueName = channel.queueDeclare().getQueue();
    	 final String corrId = UUID.randomUUID().toString();
    	 AMQP.BasicProperties props = new AMQP.BasicProperties
                 .Builder()
                 .correlationId(corrId)
                 .replyTo(replyQueueName)
                 .build();
    	 channel.basicPublish("", RPCServer.RPC_QUEUE_NAME, props, message.getBytes("UTF-8"));
    	 final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);
    	 channel.basicConsume(replyQueueName, true, new DefaultConsumer(channel) {
             @Override
             public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                 if (properties.getCorrelationId().equals(corrId)) {
                     response.offer(new String(body, "UTF-8"));
                 }
             }
         });
    	 return response.take();
     }
}
